<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        border: solid;
        display: flex;
      }
      #box input {
        flex-grow: 1;
      }
    </style>
  </head>
  <body>
    <div id="box">hello</div>
    <script>
      const box = document.getElementById("box");
      box.onclick = function () {
        const html = String.raw;
        // 1 获取box内容
        const boxContent = this.innerText;
        // 2 创建输入框
        const input = html`<input
          data-editor
          onclick="event.stopPropagation()"
          type="text"
          value="${boxContent}"
        /> `;
        // 3 将输入框覆盖到box
        box.innerHTML = input;
        // 4 获取焦点
        document.querySelector("#box input").focus();
      };

      document.addEventListener("focusout", (e) => {
        if (e.target.dataset.editor !== undefined) {
          // 1 获取编辑框内容
          const value = e.target.value;
          // 2 用编辑框内容替换box内容
          box.innerText = value;
        }
      });

      document.addEventListener("keydown", (e) => {
        if (e.target.dataset.editor !== undefined) {
          //按下回车键
          if (e.key === "Enter") {
            e.target.blur(); //失去焦点
          }
        }
      });
    </script>
  </body>
</html>
